package com.example.service;

import com.example.control.indexController;
import com.example.dao.articleMapper;
import com.example.dao.commentMapper;
import com.example.dao.statisticMapper;
import com.example.domain.t_article;
import com.example.domain.t_statistic;
import com.example.domain.t_user;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vdurmont.emoji.EmojiParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.*;
import java.util.*;

@Service
@Transactional
public class IArticleService {
    private static final Logger logger = LoggerFactory.getLogger(indexController.class);
    @Autowired
    private articleMapper art;
    @Autowired
    private statisticMapper stat;
    @Autowired
    private commentMapper comm;
    @Autowired
    private IUserService iuse;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redis;
    /**
     * 根据id查询文章详情,并使用redis缓存
     * @param id 文章唯一id
     * @return t_article
     */
    public t_article selectById(int id){

        t_article article = null;
        //从缓存中获取信息
        Object o = null;
        //System.out.println(redis);
        try{o = redis.opsForValue().get("article_" + id);}
        catch (Exception e){
            logger.error("RedisTemplate: redis == null");
        }
        if(o!=null){
            article=(t_article)o;
        }else{
            //从数据库中获取文章信息
            t_statistic statisticById = stat.getStatisticById(id);
            if(statisticById==null){
                stat.addStatistic(new t_article(id));
                statisticById = stat.getStatisticById(id);
            }
            article= art.selectArticleById(id);
            article.setHits(statisticById.getHits());
            article.setComments_num(statisticById.getComments_num());
            article.setUsername(iuse.Select(article.getUser_id()).getUsername());
            try{
                redis.opsForValue().set("article_" + article.getId(), article);
                logger.info("redis储存了：article_" + id);
            }catch (Exception e){
                logger.error("redis储存失败：article_" + id);
            }
        }
        return article;
    }

    /**
     * 分页查询
     * @param count 页码
     * @param size 每页的大小
     * @return 列表
     */
    public List<t_article> selectList(int count, int size){
        if(count<1 || size<1){

            logger.error("error:count or size"+count+","+size);
            return null;
        }
        return art.selectArticles((count-1)*size,size);
    }


    /**
     * 模糊查询
     * @param like 匹配的字符串
     * @param count 页码
     * @param size 每页的大小
     * @return
     */
    public List<t_article> selectList(String like,int count,int size){
        if(count<1 || size<1){

            logger.error("error:count or size"+count+","+size);
            return null;
        }
        if(like==null||"".equals(like))return selectList(count,size);
        return art.selectLikeArticlesPage("%"+like+"%",(count-1)*size,size);
    }
    //查询全部
    public List<t_article> selectList(){
        return art.selectGetAll();
    }
    //模糊查询全部
    public List<t_article> selectList(String like){

        if(like!=null)like=like.replace(" ","");
        if(like==null||like.equals(""))return art.selectGetAll();
        //System.out.println("%"+like+"%");
        List<t_article> t_articles = art.selectLikeArticles("%" + like + "%");
        //System.out.println(list);

        //System.out.println(art.selectLikeContentArticles("%"+like+"%"));

        return t_articles;
    }
    //查询user全部
    public List<t_article> selectList(int user_id){
        String s = iuse.SelectAuthority(user_id);
        if(s!=null&&s.contains("root")){
            return art.selectGetAll();
        }
        return art.selectGetUserAll(user_id);
    }
    //PageInfo分页,分类,精确，查询user（back）全部
    public PageInfo<t_article> getPage(int count,int size,t_article article){
        List<t_article> t_articles=null;
        //交给PageInfo自动文章分页

        if(article.getTags()!=null&&!article.getTags().equals(""))
            article.setTags("%"+article.getTags()+"%");
        if(article.getTitle()!=null&&!article.getTitle().equals(""))
            article.setTitle("%"+article.getTitle()+"%");
        if(true){ //是否查询所有分类

            String s = iuse.SelectAuthority(article.getUser_id());
            if(s!=null&&s.contains("root")){ //是否为最高权限
                PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
                t_articles = art.selectByArticles(article);
            }
            else{
                PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
                t_articles = art.selectByUserArticles(article);
            }
        }
        PageInfo<t_article> res_art = new PageInfo<>(t_articles);
        //res_art.setPageSize(Math.min(size,10));
        //res_art.setPageNum(count);
        logger.info("用户 "+article.getUsername()+" 分页的信息：页码："+count+",条数："+Math.min(size,10));
        return res_art;
    }


    //PageInfo分页(全部)模糊查询user全部
    public PageInfo<t_article> clientGetPage(String like,int count,int size,t_user us,boolean only){
        List<t_article> t_articles = null;
        like=like.replace(" ","");

        if(us!=null){
            if(this.iuse.Isroot(us)){
                if(!only){
                    if(like==null||like.equals("")) {
                        PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
                        t_articles = art.selectAll();
                    }else{
                        PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
                        t_articles = art.selectRootLikeArticles("%" + like + "%");

                    }
                    PageInfo<t_article> res_art = new PageInfo<>(t_articles);
                    return res_art;
                }
            }
            if(only){
                if(like==null||like.equals("")) {
                    PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
                    t_articles = art.selectGetUserAll(us.getId());
                }else{
                    PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
                    t_articles = art.selectLikeUserArticles("%" + like + "%", us.getId());

                }
                PageInfo<t_article> res_art = new PageInfo<>(t_articles);
                return res_art;
            }else{
                if(like==null||like.equals("")) {
                    PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
                    t_articles = art.selectGetAllByUser_id(us.getId());
                }else{
                    PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
                    t_articles = art.selectLikeUserArticlesAndAll("%" + like + "%", us.getId());

                }
                PageInfo<t_article> res_art = new PageInfo<>(t_articles);

                return res_art;
            }

        }

        //交给PageInfo自动文章分页
        if(like==null||like.equals("")) {
            PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
            t_articles = art.selectGetAll();
        }else{
            PageHelper.startPage(count,Math.min(size,10)); //设置pageinfo中的分页情况
            t_articles = art.selectLikeArticles("%" + like + "%");

        }

        PageInfo<t_article> res_art = new PageInfo<>(t_articles);
        return res_art;
    }


    //统计热度排行
    public List<t_article> selectListSort(int count,int size){
        //查找评论表
        List<t_article> res = new ArrayList<>();
        if(count<1 || size<1){
            logger.error("error:count or size"+count+","+size);
            return null;
        }
        List<t_statistic> sortPage = stat.getStatisticSortPage((count - 1) * size, size);
        for(int i=0;i<sortPage.size();i++){
            //遍历评论表
            int id = sortPage.get(i).getArticle_id(); //获得artcile_id
            //根据id查找article
            t_article article = selectById(id);
            article.setHits(sortPage.get(i).getHits());
            article.setComments_num(sortPage.get(i).getComments_num());
            res.add(article);
        }
        return res;
    }
    public List<t_article> selectListSort(){
        //查找评论表
        List<t_article> res = new ArrayList<>();
        List<t_statistic> sortPage = stat.getStatisticSort();
        for(int i=0;i<sortPage.size();i++){
            //遍历评论表
            int id = sortPage.get(i).getArticle_id(); //获得artcile_id
            //根据id查找article
            t_article article = selectById(id);
            article.setHits(sortPage.get(i).getHits());
            article.setComments_num(sortPage.get(i).getComments_num());
            res.add(article);
        }
        return res;
    }
    /**
     * 插入（发表文章）,创建评论表
     * @param article t_article
     * @return boolean
     */
    public boolean save(t_article article){
        article.setCreated(new Date());
        article.setModified(new Date());
        article.setHits(0);
        article.setComments_num(0);
        //去除表情
        article.setContent(EmojiParser.parseToAliases(article.getContent()));
        //插入文章
        art.saveArticles(article);
        //查询最后一个文章
        t_article li = art.selectArticles(1, 1).get(0);
        //根据文章查询评论表
        t_statistic lu = stat.getStatisticById(li.getId());
        //无评论表，生成评论表
        if(lu==null)stat.addStatistic(li);
        return true;
    }

    /**
     * 根据id值删除该文章,同时删除评论表以及评论
     * @param id
     * @return
     */
    public boolean deleteById(int id){
        //删除redis缓存
        try{
            redis.delete("article_"+id);
        }catch (Exception e){
            logger.error("redis delete fiailed article_"+id+",maybe redis not open");
        }
        comm.deleteAllCommentById(id);
        return art.deleteById(id) && stat.deleteStatisticByArticleId(id);
    }

    //求和
    public int count(){
        return art.countArticle();
    }
    public int count(String like){
        if(like==null||"".equals(like))count();
        return art.countLikeArticle("%"+like+"%");
    }
    //back查询所有的分类
    public List<String> getCategories(int user_id){
        String s = iuse.SelectAuthority(user_id);
        List<String> allCategories = null;
        if(s.contains("root")){
            allCategories =  art.getAllCategories();
        }else{
            allCategories =  art.getuserAllCategories(user_id);
        }
        if(allCategories==null||allCategories.size()==0){
            allCategories = new ArrayList<>();
            allCategories.add("默认分类");
        }
        return allCategories;
    }

    /**
     * 修改文章
     * @param art t_article
     * @return
     */
    public boolean updateById(t_article art){
        art.setModified(new Date());
        try{
            redis.opsForValue().set("article_" + art.getId(), null);
            logger.info("redis修改储存：article_" + art.getId());
        }catch (Exception e){
            logger.error("redis修改储存失败：article_" + art.getId());
        }
        return this.art.updateById(art);
    }


    public boolean updateTagsByUser_id(String old,String news,int user_id){
        if(old==null||old.equals("")||news==null||old.equals(news))return false;
        List<t_article> t_articles = this.art.selectGetUserAll(user_id);

        for(t_article t:t_articles){
            String tags="";
            List<String> split = Arrays.asList(t.getTags().split(","));
            for(String s:split){
                if(s.equals(old)){
                    if(!news.equals("")&&!split.contains(news)) tags+=","+news;
                }else{
                    tags+=","+s;
                }
            }

            if(tags.length()>1)tags=tags.substring(1,tags.length());
            else deleteById(t.getId());
            t.setTags(tags);
            updateById(t);
        }
        return true;
    }
    public boolean updateCateByUser_id(String old,String news,int user_id){
        if(old==null||old.equals("")||news==null||old.equals(news))return false;

        List<t_article> t_articles = art.selectGetUserAll(user_id);
        for(t_article t:t_articles){
            if(t.getCategories().equals(old)){
                if(news.equals("")){
                    deleteById(t.getId());
                }else{
                    t.setCategories(news);
                    updateById(t);
                }

            }
        }
        return true;
    }


}
